﻿import VTitle from '@/components/common/MainTitle.vue'
import SettingsDialog from './editSettings.vue'
import ShowFormLayout from '@/components/DynamicFormComponents/ShowWorkflowFormLayout.vue'
// 生成菜单的页面
import VMenu from '@/components/SetMenu.vue'
export default {
  data () {
    return {
      titleName: '流程页面管理',
      tableData: [],
      tableColumn: [
        {
          text: '名称',
          indexName: 'name'
        },
        {
          text: '路由',
          indexName: 'route'
        },
        {
          text: '类别',
          indexName: 'category'
        },
        {
          text: '是否出错',
          indexName: 'is_error'
        },
        {
          text: '是否警告',
          indexName: 'is_warnning'
        }
      ],
      // 编辑和新增的弹窗部分
      // 当前的uid
      currentUid: '',
      dialogTitle: '',
      dialogFormVisible: false,
      // 保存当前页面的配置---以便同步流程表单配置数据
      currentPageSetting: '',
      // 表单规则
      ruleForm: {
        name: '',
        desc: '',
        settings: '',
        route: '',
        category: '',
        uid: ''
      },
      labelWidth: '86px',
      operationType: '',
      rules: {
        name: [
          {required: true, message: '页面名称不能为空', trigger: 'blur'}
        ]
      },
      // 页码部分
      searchKey: '',
      // 保留输入的searchKey
      saveSearchKey: '',
      isSearch: false,
      totalData: [],
      filterData: [],
      totalLength: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      // 设置页面参数的弹窗
      showSettingsDialog: false,
      // 预览页面效果的弹窗
      priviewPageSettings: false,
      priviewPageSettingsInfo: '',
      // 生成菜单的弹窗
      menuDialog: false,
      functionObj: '',
      // 复制页面的部分
      copyLabelWidth: '120px',
      allCopyPages: [],
      copyFormVisible: false,
      copyRuleForm: {
        name: '',
        copyFormUid: '',
        desc: '',
        category: '',
        route: ''
      },
      copyRules: {
        name: [
          {required: true, message: '页面名称不能为空', trigger: 'blur'}
        ],
        copyFormUid: [
          {required: true, message: '复制的动态页面不能为空', trigger: 'change'}
        ]
      }
    }
  },
  created () {
    this.getAllPages()
  },
  methods: {
    // 初始化表格的数据
    getAllPages () {
      // 在检索的值清空前，先保存到变量saveSearchKey中
      this.saveSearchKey = this.searchKey
      this.searchKey = ''
      this.loading = true
      this.allCopyPages = []
      this.$basicWFGet('/d_form', {
        type: 'normal'
      }).then((data) => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.totalData = dataResult.data
          this.allCopyPages = dataResult.data
          this.totalLength = dataResult.data.length
          // 调用方法进行页面渲染
          this.showData(this.totalData)
          // 在编辑或者是忽略警告、解决错误时，将检索的内容保存
          if (this.operationType === 'edit' || this.operationType === 'handleError') {
            this.searchKey = this.saveSearchKey
          }
          this.loading = false
        } else {
          this.$message.error(data.data.result.msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 获取指定页面的数据
    getCurrentPageInfo () {
      this.loading = true
      this.$basicWFGet('/d_form/' + this.currentUid).then((data) => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.loading = false
          // 编辑按钮时
          if (this.operationType === 'edit') {
            this.ruleForm.name = dataResult.data.name
            this.ruleForm.desc = dataResult.data.desc
            this.ruleForm.settings = dataResult.data.settings
            // 保存历史版本的setting
            this.currentPageSetting = dataResult.data.settings
            this.ruleForm.route = dataResult.data.route
            this.ruleForm.category = dataResult.data.category
            this.ruleForm.uid = dataResult.data.uid
            this.dialogFormVisible = true
          } else if (this.operationType === 'preview') {
            // 预览按钮时
            if (dataResult.data.settings) {
              this.priviewPageSettingsInfo = JSON.parse(dataResult.data.settings)
              if (this.priviewPageSettingsInfo.list.length) {
                this.priviewPageSettings = true
              } else {
                this.$message({
                  message: '该页面还没有设置参数，请先点击编辑按钮进行页面参数设置',
                  type: 'warning'
                })
              }
            } else {
              this.$message({
                message: '该页面还没有设置参数，请先点击编辑按钮进行页面参数设置',
                type: 'warning'
              })
            }
          } else if (this.operationType === 'delete') {
            // 删除时
            this.deleteMethod(dataResult.data.settings)
          }
        } else {
          this.$message.error(data.data.result.msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 点击预览的按钮
    handlePreview (row) {
      this.currentUid = row.uid
      this.getCurrentPageInfo()
      this.operationType = 'preview'
    },
    // 点击生成页面的按钮---弹出选择菜单的页面
    getDefinePage (row) {
      this.functionObj = {
        funcName: row.name,
        funcAuth: '',
        funcUid: row.uid,
        from: 'workflowMenu'
      }
      this.menuDialog = true
    },
    // 添加页面
    handleAdd () {
      this.dialogFormVisible = true
      this.dialogTitle = '添加流程页面基本信息'
      this.ruleForm.name = ''
      this.ruleForm.desc = ''
      this.ruleForm.settings = ''
      this.ruleForm.route = ''
      this.ruleForm.category = ''
      this.operationType = 'add'
      this.currentPageSetting = ''
    },
    // 编辑页面
    handleEdit (row) {
      this.dialogTitle = '编辑流程页面基本信息'
      this.currentUid = row.uid
      this.currentPageSetting = ''
      this.getCurrentPageInfo()
      this.operationType = 'edit'
    },
    // 复制页面
    handleCopy () {
      this.copyFormVisible = true
      this.copyRuleForm.name = ''
      this.copyRuleForm.copyFormUid = ''
      this.copyRuleForm.desc = ''
      this.copyRuleForm.route = ''
      this.copyRuleForm.category = ''
      this.currentPageSetting = ''
    },
    // 删除页面
    handleDelete (row) {
      this.currentPageSetting = ''
      this.$confirm('此操作将永久删除该页面, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.currentUid = row.uid
        this.getCurrentPageInfo()
        this.operationType = 'delete'
      }).catch(() => {})
    },
    // 删除的方法
    deleteMethod (pageSettingJson) {
      this.loading = true
      this.$basicWFDelete('/d_form/' + this.currentUid).then((data) => {
        this.loading = false
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          // 同步流程表单配置数据---1更新，2删除
          this.syncWorkflowFormConfig(pageSettingJson, 2, '删除成功')
        } else {
          this.$message.error(data.data.result.msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 提交编辑的方法
    submitEdit () {
      this.loading = true
      this.$basicWFPatch('/d_form/' + this.currentUid, {
        name: this.ruleForm.name,
        desc: this.ruleForm.desc,
        settings: this.ruleForm.settings,
        route: this.ruleForm.route,
        category: this.ruleForm.category,
        type: 'normal'
      }).then((data) => {
        this.loading = false
        if (data.data.result.code === 'success') {
          // 同步流程表单配置数据---1更新，2删除
          this.syncWorkflowFormConfig(this.ruleForm.settings, 1, '编辑成功')
        } else {
          this.$message.error(data.data.result.msg)
        }
      })
    },
    // 提交新增的方法
    submitAdd () {
      this.loading = true
      this.$basicWFPost('/d_form', {
        name: this.ruleForm.name,
        desc: this.ruleForm.desc,
        settings: this.ruleForm.settings,
        route: this.ruleForm.route,
        category: this.ruleForm.category,
        type: 'normal'
      }).then((data) => {
        this.loading = false
        if (data.data.result.code === 'success') {
          this.currentUid = data.data.result.uid
          // 同步流程表单配置数据---1更新，2删除
          this.syncWorkflowFormConfig(this.ruleForm.settings, 1, '添加成功')
        } else {
          this.$message.error(data.data.result.msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 点击弹窗的确定按钮
    submitForm (forms, submitType) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          if (submitType === 'edit') {
            this.submitEdit()
          } else if (submitType === 'add') {
            this.submitAdd()
          }
        } else {
          return false
        }
      })
    },
    // 点击弹窗的取消按钮
    resetForm (forms) {
      this.$refs[forms].clearValidate()
      this.dialogFormVisible = false
    },
    closeDialog () {
      this.$refs.ruleForm.clearValidate()
    },
    // 关闭复制页面的窗口
    closeCopyDialog () {
      this.$refs.copyRuleForm.clearValidate()
    },
    // 点击复制页面弹窗的取消按钮
    resetCopyForm (forms) {
      this.$refs[forms].clearValidate()
      this.copyFormVisible = false
    },
    // 确定按钮
    submitCopyForm (forms) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          this.loading = true
          // 先获取关联到页面的详细
          this.$basicWFGet('/d_form/' + this.copyRuleForm.copyFormUid).then((data) => {
            let dataResult = data.data.result
            if (dataResult.code === 'success') {
              var requestData = {
                name: this.copyRuleForm.name,
                desc: this.copyRuleForm.desc,
                settings: dataResult.data.settings,
                route: this.copyRuleForm.route,
                category: this.copyRuleForm.category,
                type: 'normal'
              }
              this.$basicWFPost('/d_form', requestData).then((data) => {
                this.loading = false
                if (data.data.result.code === 'success') {
                  this.currentUid = data.data.result.uid
                  // 同步流程表单配置数据---1更新，2删除
                  this.syncWorkflowFormConfig(dataResult.data.settings, 1, '复制成功')
                } else {
                  this.$message.error(data.data.result.msg)
                }
              }).catch((error) => {
                console.log(error)
              })
            } else {
              this.$message.error(data.data.result.msg)
              this.loading = false
            }
          }).catch((error) => {
            console.log(error)
          })
        } else {
          return false
        }
      })
    },
    // 将页码与数据关联
    showData (myData) {
      // 渲染表格的数据存放在 this.tableData 中
      this.tableData = []
      if (myData.length) {
        let from = (this.currentPage - 1) * this.pageSize
        let to = this.currentPage * this.pageSize
        if (to > myData.length) {
          to = myData.length
        }
        for (; from < to; from++) {
          this.tableData.push(myData[from])
        }
      }
    },
    // 底部页码的部分
    handleSizeChange (val) {
      this.pageSize = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    },
    handleCurrentChange (val) {
      this.currentPage = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    },
    // 设置页面参数的弹窗相关方法
    sureEditSetting (fromSettings) {
      this.showSettingsDialog = false
      this.ruleForm.settings = fromSettings.jsonData
      this.ruleForm.category = fromSettings.category
    },
    editSettingsForm () {
      if (!this.ruleForm.name) {
        this.$message({
          message: '请先设置动态页面名称',
          type: 'warning'
        })
      } else {
        this.showSettingsDialog = true
      }
    },
    // 同步流程表单配置数据的方法
    syncWorkflowFormConfig (pageJson, actionType, msg) {
      if (pageJson) {
        let pageSettingObj = JSON.parse(pageJson)
        let pageConfig = pageSettingObj.pageConfig
        if (pageConfig.hadWorkflow && pageConfig.relatedWorkflow && pageConfig.relatedWorkflowNode) {
          this.syncWorkflowFormConfigMethod(pageConfig.relatedWorkflow, this.currentUid, pageConfig.relatedWorkflowNode, actionType, msg)
        } else {
          // 当第一次设有流程编辑时取消流程时
          if (this.currentPageSetting) {
            let pageSettingObjCurrent = JSON.parse(this.currentPageSetting)
            let pageConfigCurrent = pageSettingObjCurrent.pageConfig
            if (pageConfigCurrent.hadWorkflow && pageConfigCurrent.relatedWorkflow && pageConfigCurrent.relatedWorkflowNode) {
              actionType = 2
              this.syncWorkflowFormConfigMethod(pageConfigCurrent.relatedWorkflow, this.currentUid, pageConfigCurrent.relatedWorkflowNode, actionType, msg)
            } else {
              if (msg === '编辑成功' || msg === '添加成功') {
                this.dialogFormVisible = false
              } else if (msg === '复制成功') {
                this.copyFormVisible = false
              }
              this.getAllPages()
              this.$message({
                type: 'success',
                message: msg
              })
            }
          } else {
            if (msg === '编辑成功' || msg === '添加成功') {
              this.dialogFormVisible = false
            } else if (msg === '复制成功') {
              this.copyFormVisible = false
            }
            this.getAllPages()
            this.$message({
              type: 'success',
              message: msg
            })
          }
        }
      }
    },
    syncWorkflowFormConfigMethod (WFID, FormID, NodeID, ActionType, msg) {
      this.$basicWFPost('/WorkFlowMgr/SyncWorkflowFormConfig', {
        WFID: WFID,
        FormID: FormID,
        NodeID: NodeID,
        ActionType: ActionType
      }).then(data => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          if (msg === '编辑成功' || msg === '添加成功') {
            this.dialogFormVisible = false
          } else if (msg === '复制成功') {
            this.copyFormVisible = false
          }
          this.getAllPages()
          this.$message({
            type: 'success',
            message: msg
          })
        } else if (dataResult.code === 'failed') {
          this.$message({
            type: 'error',
            message: dataResult.msg
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 忽略警告校正错位的按钮
    handleError (row, route) {
      let msg = route === 'correct' ? '确定该动态表单已修改正确，现进行校正？' : '忽略该动态表单的警告？'
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.loading = true
        this.operationType = 'handleError'
        this.$basicWFPatch('/d_form/' + row.uid + '/' + route).then((data) => {
          this.loading = false
          if (data.data.result.code === 'success') {
            this.$message({
              message: data.data.result.msg,
              type: 'success'
            })
            this.getAllPages()
          } else {
            this.$message.error(data.data.result.msg)
          }
        })
      }).catch(() => {})
    },
    // 表格中的下拉菜单
    handleCommand (command) {
      switch (command.index) {
        case 1: {
          // 生成菜单
          this.getDefinePage(JSON.parse(command.rowData))
          break
        }
        case 2: {
          // 校正错误
          this.handleError(JSON.parse(command.rowData), 'correct')
          break
        }
        case 3: {
          // 忽略错误
          this.handleError(JSON.parse(command.rowData), 'ignore_warn')
          break
        }
        case 4: {
          // 删除
          this.handleDelete(JSON.parse(command.rowData))
          break
        }
      }
    }
  },
  watch: {
    // 搜索的功能
    searchKey: {
      handler: function (val, oldVal) {
        // 当检索的内容为空时需要将表格的内容还原
        if (this.$trim(val) === '') {
          this.pageSize = 10
          this.currentPage = 1
          this.totalLength = this.totalData.length
          this.isSearch = false
          // 调用方法进行页面渲染
          this.showData(this.totalData)
        } else {
          // 检索结果的数据存放在 this.filterData 中
          this.filterData = []
          this.totalData.forEach((value, index) => {
            if (value.name) {
              if (value.name.indexOf(this.searchKey) >= 0) {
                this.filterData.push(value)
              }
            }
          })
          this.isSearch = true
          this.currentPage = 1
          this.totalLength = this.filterData.length
          // 调用方法进行页面渲染
          this.showData(this.filterData)
        }
      },
      deep: true
    }
  },
  components: {
    VTitle, SettingsDialog, ShowFormLayout, VMenu
  }
}
